package com.lyl.serviceedu.controller;


import com.lyl.commonutils.R;
import com.lyl.serviceedu.cloudclient.VodClient;
import com.lyl.serviceedu.entity.Video;
import com.lyl.serviceedu.service.VideoService;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-06-14
 */
@RestController
@RequestMapping("/serviceedu/video")
public class VideoController {
    @Autowired
    private VideoService videoService;

    @Autowired
    VodClient vodClient;

    @ApiOperation("根据id获取小节信息")
    @GetMapping("{id}")
    public R getById(@PathVariable Long id) {

        return R.ok().data("data",videoService.getById(id));
    }


    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody Video eduVideo) {
        System.out.println("eduVideo:"+ eduVideo);
        videoService.save(eduVideo);
        return R.ok();
    }

    //添加小节
    @PutMapping("updateVideo")
    public R updateVideo(@RequestBody Video eduVideo) {
        System.out.println("eduVideo:"+ eduVideo);
        videoService.updateById(eduVideo);
        return R.ok();
    }

    //删除小节

    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable Long id) {

       //1.  先删除小节对应的视频
        Video video= videoService.getById(id);


       if(!StringUtils.isNullOrEmpty(video.getVideoSourceId())){
           vodClient.removeVideo(video.getVideoSourceId());//  删除视频
       }
//        远程调用vod服务删除视频

        //2.删除小节
        boolean isOk= videoService.removeVideoById(id);
        if(isOk) {
            return R.ok().message("删除成功");
        }else{
            return R.error().message("删除失败");
        }
    }



    @PutMapping("updateByDeleteVod/{videoSourceId}")
    public R updateByDeleteVod(@PathVariable(name = "videoSourceId") String videoSourceId
                                ,@RequestBody Video video) {

        // 1.远程调用 根据视频id 删除视频
       R result= vodClient.removeVideo(videoSourceId);

        //2. 修改 视频表 视频资源 以及文件名为 ""
        if(result.getSuccess()) {
            video.setVideoSourceId("");
            video.setVideoOriginalName("");
            if (videoService.updateById(video)) {// 修改小节
                return R.ok();
            }

        }
        return R.error();

    }
}

